<template>
  <div class="code-layout">
    <div class="list-box">
      <div class="list-item">
        <span>Group by：</span>
        <el-select v-model="group" placeholder="请选择分组">
          <el-option :label="item.name" :value="item.id" v-for="item in groups" :key="item.id"></el-option>
        </el-select>
      </div>
      <div class="list-item">
        <span>容器：</span>
        <p v-if="podMap.length == 1" class="pod-name">{{ podName }}</p>
        <el-select v-else v-model="podName" class="pod-name-select" placeholder="请选择" @change="selectPod">
          <el-option v-for="item in podMap" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </div>

      <div class="list-item tooltip-bar">
        <span>平滑：</span>
        <el-slider class="tooltip" v-model="tooltip" :format-tooltip="formatTooltip" />
      </div>

      <div class="metrice-list-box">
        <div class="title">指标列表</div>
        <ul class="metrice-list-container">
          <li v-for="item in metrics" :key="item.id" :class="`metrice-item ${item.show ? '' : 'is-hide'}`"
            @click="item.show = !item.show">
            {{ item.key }}
          </li>
        </ul>
        <div class="title">资源列表</div>
        <ul class="metrice-list-container">
          <!-- <li :class="`metrice-item ${gpuData.show ? '' : 'is-hide'}`" @click="gpuData.show = !gpuData.show">GPU</li> -->
          <!-- <li :class="`metrice-item ${cpuData.show ? '' : 'is-hide'}`" @click="cpuData.show = !cpuData.show">CPU</li> -->
          <!-- <li :class="`metrice-item ${memData.show ? '' : 'is-hide'}`" @click="memData.show = !memData.show">MEM</li> -->
          <li class="metrice-item">GPU</li>
          <li class="metrice-item">CPU</li>
          <li class="metrice-item">MEM</li>
        </ul>
      </div>
    </div>

    <div style="width: 100%">
      <el-button type="primary" style="float: right" @click="exportData">下载pdf</el-button>
      <div class="container" id="container">
        <h3>资源监控</h3>
        <div class="container-item resource">
          <v-chart :option="gpuData" class="chart-item" v-if="gpuData.show" />
          <v-chart :option="cpuData" class="chart-item" v-if="cpuData.show" />
          <v-chart :option="memData" class="chart-item" v-if="memData.show" />
        </div>
        <h3>指标监控</h3>
        <div class="container-item target">
          <div class="metrics">
            <div v-for="e in plots" :key="e.key" class="metrics-item">
              <metrics-chart-bar :metricData="getMetricData" :option_cfg="e"
                v-if="e && e.value && e.plot_type == 'bar'" />
              <metrics-chart-pie :metricData="getMetricData" :option_cfg="e"
                v-if="e && e.value && e.plot_type == 'pie'" />
              <metrics-chart-scatter :metricData="getMetricData" :option_cfg="e"
                v-if="e && e.value && e.plot_type == 'scatter'" />
            </div>
            <template v-for="(e, i) in metrics">
              <div class="metrics-item" v-if="e.show" :key="i">
                <metrics-chart :metricData="getMetricData" :option_cfg="e" />
              </div>
            </template>
          </div>
        </div>


      </div>
    </div>
  </div>
</template>

<script>

import { getexperimentPodName, metricKeys, metricData } from '@/api/notebook'
import { usageDuration } from '@/api/dashboard'
import metricsChart from '@/components/module/metrics-chart'
import metricsChartBar from '@/components/module/metrics-chart-bar'
import metricsChartPie from '@/components/module/metrics-chart-pie'
import metricsChartScatter from '@/components/module/metrics-chart-scatter'
import { formatTime } from "@/utils/tool";
import htmlToPdf from '@/utils/printPDF';

export default {
  data() {
    return {
      podName: '',
      podMap: [],
      gpuData: {},
      gpuMemData: {},
      cpuData: {},
      memData: {},
      logSocket: null,
      logMsg: null,
      logData: [],
      metrics: [],
      plots: [],
      group: "",
      groups: [],
      tooltip: 0,

    };
  },
  props: ['detailData'],
  components: {
    metricsChart,
    metricsChartBar,
    metricsChartPie,
    metricsChartScatter
  },
  watch: {
    async detailData(val) {
      console.log("val", val)
      if (val.status === 'running') {
        await this.getPod()
        this.selectPod()
      }
    }
  },
  methods: {
    exportData() {
      htmlToPdf.downloadPDF(document.querySelector('#container'), '测试pdf2');
    },
    formatTooltip(val) {
      return val / 100;
    },
    async getPod() {
      let res = await getexperimentPodName({ id: this.$route.query.id })
      this.podName = res.data[0]
      this.podMap = res.data
      return
    },
    async getduration(pod_name, resource_type) {
      return await usageDuration({
        end: formatTime(new Date().getTime()),
        pod_name,
        resource_type,
        start: formatTime(new Date().getTime() - 1000 * 60 * 60 * 1),
        step: "15s",
      })
    },

    async renderMonitoring() {
      let gpu = await this.getduration(this.podName, 'gpu')
      let gpuMem = await this.getduration(this.podName, 'gpu_mem')
      let cpu = await this.getduration(this.podName, 'cpu')
      let mem = await this.getduration(this.podName, 'mem')
      gpu.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      gpuMem.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      cpu.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      mem.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      gpu.data.title = 'GPU-UTIL'
      gpuMem.data.title = 'GPU-MEM'
      cpu.data.title = 'CPU'
      mem.data.title = 'MEM'
      this.gpuData = { ...gpu.data, show: true }
      // this.gpuMemData = gpuMem.data
      this.cpuData = { ...cpu.data, show: true }
      this.memData = { ...mem.data, show: true }
    },
    toBottom() {
      let sH = this.$refs.logBox && this.$refs.logBox.scrollHeight;
      let sT = this.$refs.logBox && this.$refs.logBox.scrollTop;
      let oH = this.$refs.logBox && this.$refs.logBox.offsetHeight;
      if (sH - sT < oH + 40) {
        this.$refs.logBox.scrollTop = this.$refs.logBox.scrollHeight;
      } else {
        console.log(
          "断掉数据push，并且存储到临时容器。 当滚动条滚动到底部的时候 再把临时数据塞进正常ui"
        );
      }
    },
    msgFn(e) {
      if (e.data === "ws message received") return;
      console.log(e.data)
      if (this.logData.length > this.num * 30) {
        this.logData.shift();
        this.logData.push(e.data.replace(/\n/g, "<br />"));
      } else {
        this.logData.push(e.data.replace(/\n/g, "<br />"));
      }
      this.toBottom();
    },

    async getMetricData(id, key, type) {
      let ret = await metricData({ id: id, key: key, type: type })
      return ret
    },
    async renderMetric() {

      let metricsKey = await metricKeys({ id: this.$route.query.id, type: 'metrics' })
      let plotsKey = await metricKeys({ id: this.$route.query.id, type: 'plots' })
      this.metrics = []
      metricsKey.data.forEach(async e => {
        let option_cfg = {
          id: this.$route.query.id,
          key: e,
          type: 'metrics',
          show: true
        }
        this.metrics.push(option_cfg)
      })
      this.plots = []
      plotsKey.data.forEach(async e => {
        let ret = await metricData({ id: this.$route.query.id, key: e, type: 'plots' })
        let item = ret.data[0]
        let option_cfg = {
          id: this.$route.query.id,
          key: e,
          type: 'plots',
          value: item.value,
          plot_type: item.plot_type
        }
        this.plots.push(option_cfg)
      })
    },
    selectPod() {
      this.renderMonitoring(this.podName)
      //this.renderMetric()
    },
  },
  async mounted() {
    console.log("detailData", this.detailData)
    if (this.detailData.status === 'running') {
      await this.getPod()
      this.selectPod()
      this.renderMonitoring(this.podName)
    }
    this.renderMetric()

  }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/code.less";

.chart-item {
  height: 320px;
}

.log {
  background: #000;
  padding: 20px;
  margin: 20px 0 0;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.6);
  min-height: 400px;

  .log-box {
    overflow-x: hidden;
    overflow-y: auto;
    padding-right: 10px;

    .log-lis {
      color: #999;
      font-size: 12px;
    }
  }
}

.metrics {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .metrics-item {
    width: 50%;
    height: 400px;
  }
}
</style>
